import type {
  CaptchaVo,
} from '#/auth/captcha'
import type {
  LoginState,
  LoginSuccessVo,
  OauthLoginState,
} from '#/auth/Login'
import { http } from '@/utils/request/index'

/**
 * 登录
 * @param data
 * @returns Promise<LoginSuccessVo>
 */
export function loginApi(data: LoginState | OauthLoginState) {
  return http.request<LoginSuccessVo>('post', '/auth/oauth2/token', {
    data,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Authorization': `Basic ${getAuthorization()}`,
    },
  })
}

/**
 * 获取登录验证码
 * @returns CaptchaVo
 */
export function getLoginCodeApi(type: 'SMS' | 'ARITHMETIC' | 'CHINESE' | 'SPEC') {
  return http.request<CaptchaVo>('get', `/admin-api/system/oauth2/code/login`, {
    params: {
      type,
    },
  })
}

/**
 * 加密客户端信息
 * @returns btoa
 */
function getAuthorization() {
  const clientId = import.meta.env.VITE_AUTH_CLIENT_ID
  const clientSecret = import.meta.env.VITE_AUTH_CLIENT_SECRET
  return btoa(`${clientId}:${clientSecret}`)
}
